package com.yuma.pool;

import java.util.concurrent.*;

public class ExecutorsDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1.固定大小线程池: 核心线程数 = 最大线程数 = size
        /*ExecutorService executorService = Executors.newFixedThreadPool(3);

        for(var i = 0; i < 10; i++){
            executorService.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ":办理业务");
            });
        }
        */

        // 2.单线程线程池：核心线程数 = 最大线程数 = 1
        /*ExecutorService executorService = Executors.newSingleThreadExecutor();
        for(var i = 0; i < 10; i++){
            executorService.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ":办理业务");
            });
        }
        executorService.shutdown();*/

        // 3.缓存线程池：核心线程数 = 0，最大线程数 = Integer.MAX_VALUE，
        ExecutorService executorService2 = Executors.newCachedThreadPool();
        for(var i = 0; i < 1000; i++){
            Future<Integer> future = executorService2.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ":办理业务");
                return ThreadLocalRandom.current().nextInt();  // Callable接口
            });
            System.out.println(future.get());
        }

        executorService2.shutdown();

        // 4.延时线程池：核心线程数 = size，最大线程数 = Integer.MAX_VALUE，
        ScheduledExecutorService executorService3 = Executors.newScheduledThreadPool(3);
        for (var i = 0; i < 1000; i++){
            executorService3.schedule(()->{
                System.out.println(Thread.currentThread().getName()+":办理业务");
            },30, TimeUnit.SECONDS);
        }

        // 池子使用完必须关闭
        executorService3.shutdown();
    }
}
